package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.common.exception.CustomException;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentHotServiceimpl implements CommentHotService {

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //参数校验
        if (entryId == null || apComment == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //根据文章id查询所有评论
        // 并按点赞降序排序
        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId)).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);

        List<ApComment> commentList = apCommentList.stream().limit(5).collect(Collectors.toList());

        //点赞排名前5名的点赞数大于5改为热评
        for (ApComment comment : commentList) {
            if (comment.getLikes() > 5) {
                comment.setFlag((short) 1);
                mongoTemplate.save(comment);
            }
        }

        //排名低于5的全改为普通文章
        for (int i = 5; i <= apCommentList.size(); i++) {
            ApComment comment = apCommentList.get(i);
            comment.setFlag((short) 0);
            mongoTemplate.save(comment);
        }

    }
}
